window.onload = function() {
    // 初始化ajax
    ajax.config.state({
        200: true,
        201: true
    });
    // 获取初始化数据
    getInitDatabase();
}

// 开奖区间
var section = {
    // 开盘时间
    min: ('09:02:00').replace(/:/gi, ''),
    // 封盘时间
    max: ('23:57:00').replace(/:/gi, ''),
    // 计算北京时间和本地时间之差
    calc: 0,
    // 上一期期号
    prevno: 0
};

// 获取初始化数据
function getInitDatabase() {
    ajax.get('http://sg.51hub.cn/api?pk10.init', function(res) {
        if(res.state) {
            var list = res.data;
            // 计算北京时间和本地时间之差
            var now = parseInt(new Date().getTime() / 1000);
            section.calc = list.bj_time - now;
            // 开始计时
            itemTimeout.bjtime.jude = true;
            itemTimeout.bjtime.init();
            // 始终获取一次开奖结果
            realcollect.init();
        }
    });
}

// 断点，刷新页面
var duandian = {
	// 1个小时刷新一次
	max: 1 * 60 * 60,
	index: 1
};

// 计时器集合
var itemTimeout = {
    // 北京时间
    bjtime: {
        jude: false,
        init: function() {
            /*var self = itemTimeout.bjtime;
            if(self.jude) {
                var now = parseInt(new Date().getTime() / 1000) + Number(section.calc);
                // 判定
                determine(now);
                setTimeout(function() {
                    self.init();
                }, 1000);
            }*/

            var worker = new Worker("../../../../public/triplan/js/collect.real.work.js");

            // 传参给子线程
            worker.postMessage({
                calc: section.calc
            });

            //设置postMessage的监听
            worker.onmessage = function(message) {
                var list = message.data;
                determine(list.now);
                if (duandian.index >= duandian.max) {
                		window.location.reload();
                } else {
                		++duandian.index;
                }
                // 传参给子线程
                /*worker.postMessage({
                    calc: section.calc
                });*/
                // terminate 方法用于停止worker的继续运行
                //worker.terminate();
            };

            // 监听报错
            worker.onerror = function(error) {
                worker.terminate();
                console.log(error.filename, error.lineno, error.message);
            }
        }
    }
};

// 判定
function determine(bjtime) {
    // 获取时分
    var hhiiss = tool.formatDate('hhiiss', bjtime);
    // 判断是否开盘
    var domNextno = document.querySelector('#ipt-nextno');
    if(detection.isopen(hhiiss)) {
        // 倒计时
        if(!domNextno.getAttribute('data-nextno')) {
            domNextno.innerHTML = '已开盘';
        }
        detection.distance(bjtime);
    } else {
        domNextno.innerHTML = '未开盘';
    }
}

// 检测
var detection = {
    // 检测是否开盘
    isopen: function(hhiiss) {
        if(hhiiss > section.min && hhiiss < section.max) {
            return true;
        } else {
            return false;
        }
    },
    // 检测距离下一次开奖还有多久时间
    distance: function(now) {
        var ii = tool.formatDate('ii', now);
        var i = String(ii)[1];
        var ss = Number(tool.formatDate('ss', now));
        // 判断大于02分还是大于07分
        var dif_i = 0;
        var dif_s = 59;
        if(i < 2) {
            // 下期开奖时间*2分
            dif_i = 2;
        } else if(i >= 2 && i < 7) {
            // 下期开奖时间*7分
            dif_i = 7;
        } else if(i >= 7) {
            // 下期开奖时间*2分
            dif_i = 7 + 5;
        }
        var res_i = Math.abs(Number(dif_i) - 1 - Number(i));
        var res_s = Math.abs(dif_s - ss);
        var res_ii = '0' + res_i;
        var res_ss = res_s > 9 ? res_s : '0' + res_s;
        document.querySelector('#ipt-countdown').innerHTML = res_ii + ':' + res_ss;
        detection.islottery(res_i, res_s);
    },
    // 是否到时间开奖
    islottery: function(res_i, res_s) {
        if(Number(res_i) == 0 && Number(res_s) == 0) {
            // 开奖
            document.querySelector('#ipt-nextno').innerHTML = '开奖中';
            // 延迟30秒再访问结果
            setTimeout(function() {
                realcollect.init();
            }, 30 * 1000);

        }
    }
};

// 计算下一期的期号
function nextno(no) {
    // no 当前期号
    return Number(no) + 1;
}

// 采集开奖结果
var realcollect = {
    // 是否执行中
    isrun: false,
    again: 1,
    init: function() {
        var self = realcollect;
        // 已执行中，不可再执行
        if(self.isrun) return;
        // 开始执行
        self.isrun = true;
        ajax.get('http://sg.51hub.cn/api?pk10.realCollect', function(res) {
            // 执行结束
            self.isrun = false;
            if(res.state) {
                // 判断本次期号与上期期号
                if(section.prevno == res.data.no) {
                    // 期号一致，可能数据暂时没刷新，每隔1.5秒再次刷新
                    setTimeout(function() {
                        self.init();
                    }, 1500);
                } else {
                    console.dir('prevno: ' + section.prevno);
                    // 记录本期期号为上一期期号
                    section.prevno = res.data.no;
                    console.dir('nowno: ' + res.data.no);
                    // 期号不一致，正常显示
                    document.querySelector('#ipt-nextno').setAttribute('data-nextno', nextno(res.data.no));
                    document.querySelector('#ipt-nextno').innerHTML = nextno(res.data.no);
                    console.dir('nextno: ' + nextno(res.data.no));
                    createDatabase(res.data);
                }
            } else {
//              // 异常可重复执行三次
//              if(self.again < 3) {
//                  ++self.again;
//                  self.init();
//              } else {
//                  self.again = 1;
//              }
				setTimeout(function(){
					self.init();
				}, 1000);
            }
        });
    }
};

function createDatabase(data) {
    var list = data;
    var ele = '';
    var domDiv = document.createElement('div');
    domDiv.className = 'livebox';
    ele += '<p class="text-center">';
    ele += '<small class="fs12r">第<font class="p-x-1x">' + list.no + '</font>期开奖号码</small>';
    ele += '</p>';
    ele += '<ul class="awardresults p-y-2x">';
    for(var i in list.list) {
        var num = list.list[i];
        ele += '<li>';
        ele += '<img class="numbar" src="../../../../public/index/image/numresults/' + Number(num) + '.svg" />';
        ele += '</li>';
    }
    ele += '</ul>';
    ele += '<div class="winresults dis-table m-b-1x">';
    ele += '<span class="dis-cell line-right">';
    ele += '<img style="height: 28px; float: left;" src="../../../../public/index/image/numresults/' + Number(list.list[0]) + '.svg" />';
    ele += '<font class="p-x-1x line-right">冠</font>';
    ele += '<font class="p-x-1x">' + winrule.compare.sord(list.list[0]) + '</font>';
    ele += '<font class="p-x-1x">' + winrule.compare.bors(list.list[0]) + '</font>';
    ele += '</span>';
    ele += '<span class="dis-cell">';
    ele += '<img style="height: 28px; float: left;" src="../../../../public/index/image/numresults/' + Number(list.list[1]) + '.svg" />';
    ele += '<font class="p-x-1x line-right">亚</font>';
    ele += '<font class="p-x-1x">' + winrule.compare.sord(list.list[1]) + '</font>';
    ele += '<font class="p-x-1x">' + winrule.compare.bors(list.list[1]) + '</font>';
    ele += '</span>';
    ele += '</div>';
    ele += '<div class="winresults dis-table text-center">';
    ele += '<div class="dis-cell line-right">';
    ele += '<p class="line-bottom">1-5龙虎</p>';
    ele += '<ul class="dis-table linefive">';
    // [1|10]
    ele += '<li class="dis-cell line-right">' + winrule.longhu(list.list[0], list.list[9]) + '</li>';
    // [2|9]
    ele += '<li class="dis-cell line-right">' + winrule.longhu(list.list[1], list.list[8]) + '</li>';
    // [3|8]
    ele += '<li class="dis-cell line-right">' + winrule.longhu(list.list[2], list.list[7]) + '</li>';
    // [4|7]
    ele += '<li class="dis-cell line-right">' + winrule.longhu(list.list[3], list.list[6]) + '</li>';
    // [5|6]
    ele += '<li class="dis-cell">' + winrule.longhu(list.list[4], list.list[5]) + '</li>';
    ele += '</ul>';
    ele += '</div>';
    ele += '<div class="dis-cell">';
    ele += '<p class="line-bottom">冠亚和</p>';
    ele += '<ul class="dis-table linethree">';
    ele += '<li class="dis-cell line-right">' + winrule.aband.andor(list.list[0], list.list[1]) + '</li>';
    ele += '<li class="dis-cell line-right">' + winrule.aband.sord(list.list[0], list.list[1]) + '</li>';
    ele += '<li class="dis-cell">' + winrule.aband.bors(list.list[0], list.list[1]) + '</li>';
    ele += '</ul>';
    ele += '</div>';
    ele += '</div>';
    domDiv.innerHTML = ele;
    document.querySelector('#databaseVlist').insertBefore(domDiv, document.querySelector('#databaseVlist').getElementsByTagName('div')[0]);
}

// 规则计算
var winrule = {
    // 龙虎计算
    longhu: function() {
        if(Number(arguments[0]) > Number(arguments[1])) {
            return '龙';
        } else {
            return '虎';
        }
    },
    // “冠” “亚” 比较
    compare: {
        // 比大小
        bors: function() {
            if(arguments[0] <= 5) {
                return '小';
            } else {
                return '大';
            }
        },
        // 比单双
        sord: function() {
            if(arguments[0] % 2 == 1) {
                return '单';
            } else {
                return '双';
            }
        }
    },
    // 冠亚和
    aband: {
        // “冠亚和”比大小
        bors: function() {
            var val = Number(arguments[0]) + Number(arguments[1]);
            if(val <= 11) {
                return '小';
            } else {
                return '大';
            }
        },
        // “冠亚和”比单双
        sord: function() {
            var val = Number(arguments[0]) + Number(arguments[1]);
            if(val % 2 == 1) {
                return '单';
            } else {
                return '双';
            }
        },
        // “冠亚和”
        andor: function() {
            var val = Number(arguments[0]) + Number(arguments[1]);
            return val;
        }
    }
};